#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import http.server
import socketserver
import json
import webbrowser
from datetime import datetime

# 城市列表
CITIES = [
    '北京', '上海', '广州', '深圳', '成都', '重庆', '西安', '武汉',
    '南京', '杭州', '天津', '青岛', '厦门', '长沙', '郑州', '合肥',
    '济南', '福州', '南昌', '石家庄', '太原', '呼和浩特', '沈阳', '大连',
    '长春', '哈尔滨', '昆明', '贵阳', '南宁', '海口', '三亚', '兰州',
    '西宁', '银川', '乌鲁木齐', '拉萨', '池州', '东至', '东至县'
]

class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/frontend/index.html'
        elif self.path == '/api/status':
            self.send_api_status()
        elif self.path == '/api/cities':
            self.send_cities()
        else:
            super().do_GET()
    
    def send_api_status(self):
        """发送API状态"""
        status = {
            'success': True,
            'status': 'success',
            'message': '简化版服务器运行正常',
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'features': [
                '🌍 全国城市支持',
                '⚡ 快速响应',
                '🎯 支持小城市'
            ]
        }
        self.send_json_response(status)
    
    def send_cities(self):
        """发送城市列表"""
        self.send_json_response({
            'success': True,
            'cities': CITIES
        })
    
    def send_json_response(self, data):
        self.send_response(200)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        
        json_data = json.dumps(data, ensure_ascii=False, indent=2)
        self.wfile.write(json_data.encode('utf-8'))

if __name__ == '__main__':
    PORT = 5003
    
    print("=" * 60)
    print(" 启动简化测试服务器")
    print("=" * 60)
    print(f"服务地址: http://localhost:{PORT}")
    print(f"前端页面: http://localhost:{PORT}/frontend/index.html")
    print("=" * 60)
    print("特性:")
    print("- 全国城市支持")
    print("- 包含东至等小城市")
    print("- 快速响应")
    print("=" * 60)
    print("按 Ctrl+C 停止服务")
    print("=" * 60)
    
    try:
        try:
            webbrowser.open(f"http://localhost:{PORT}/frontend/index.html")
        except Exception:
            pass
        with socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler) as httpd:
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"服务器启动失败: {e}")